<?php
$timestart=microtime(true);
require("config.php");
require_once(WWW_DIR."/lib/releases.php");
require_once(WWW_DIR."/lib/binaries.php");
require_once(WWW_DIR."/lib/powerprocess.php");
require_once(WWW_DIR."/lib/groups.php");
require_once(WWW_DIR."/lib/backfill.php");

$my_scan = explode( ',', $argv[1] );
clean_database();
binnewz_rss( $my_scan , $argv[2] );

function binnewz_category( $category ) {
	if ($category == '7' || $category == '26' || $category == '24' || $category == '52' || $category == '47' || $category == '11' || $category == '37' || $category == '36')
		$newznab_category='5030';
	if ($category == '44' || $category == '53')
		$newznab_category='5040';
	if ($category == '6' || $category == '23' || $category == '27' || $category == '48' || $category == '30' || $category == '31')
		$newznab_category='2030';
	if ($category == '39' || $category == '49')
		$newznab_category='2040';
	if ($category == '8')
		$newznab_category='3010';
	if ($category == '51')
		$newznab_category='3040';
	if ($category == '25')
		$newznab_category='7020';
	return $newznab_category;
}

function binnewz_rss( $scan , $month ) {
	$group_get = file_get_contents('http://www.binnews.in/_bin/newsgroup.php?country=fr');
	$group_regex = '/.*title="(.*?)".*?>(.*?)[<|\&].*/';
	$post_regex = '/.*<Titre>(.*?)<\/Titre><Archive>(.*?)<\/Archive><Taille>(.*?)<\/Taille><DatePost>(.*?)<\/DatePost><NFO>(.*?)<\/NFO><Cat>(.*?)<\/Cat><SousCat>(.*?)<\/SousCat><GUIDD>(.*?)<\/GUIDD><QuelServ>(.*?)<\/QuelServ><PourQuelMois>(.*?)<\/PourQuelMois><Anner>(.*?)<\/Anner><Langue>(.*?)<\/Langue><Resolution>(.*?)<\/Resolution><Groupe>(.*?)<\/Groupe><AutreInfo>(.*?)<\/AutreInfo><SousTitre>(.*?)<\/SousTitre><Link>(.*?)<\/Link><Comments>(.*?)<\/Comments><NBComments>(.*?)<\/NBComments><PicPhoto>(.*?)<\/PicPhoto><NumCat>(.*?)<\/NumCat><Par2>(.*?)<\/Par2>.*/';
	preg_match_all( $group_regex , $group_get , $group_matches , PREG_SET_ORDER );
	$days = floor((time() - mktime(0,0,0, date("m")-$month, date("d"), date('Y'))) / 3600 / 24)+1;
	update_site( $days );
	disable_group_all();
	disable_regex_all();
	foreach($scan as $category) {
		$cpt = $month;
		if ($cpt == 0) {
			$post_url = "http://rss.newzfinders.com/FluxRSS/SQLRSS.php?CAT=$category&MAXDAYS=3&SRV=BINNEWS";
			$post_get = get_url( $post_url );
		} else {
			$post_get = '';
			for (; $cpt > 0; $cpt--) {
				$newzfinder_date = date("Y-m", mktime(0,0,0,date("m")-$cpt+1,01,date('Y')));
				$post_url = "http://rss.newzfinders.com/FluxRSS/SQLRSS.php?CAT=$category&MOIS=$newzfinder_date&SRV=BINNEWS";
				$post_get .= get_url( $post_url );
			}
		}
		$post_get = str_replace('CHR(")/CHR', '\'', $post_get);
		preg_match_all( $post_regex , $post_get , $post_matches , PREG_SET_ORDER );
		add_group_post( $group_matches , $post_matches , $days+6 );
		add_regex_post( $post_matches , binnewz_category( $category ) );
	}
	$dir = dirname(__FILE__);
    $output = shell_exec("php {$dir}/update_binaries.php");
	echo $output;
	$output = shell_exec("php {$dir}/backfill.php");
    echo $output;
	$releases = new Releases;
	$releases->processReleases();
	update_release_post( $post_matches );
	del_regex_post();
}

function update_site( $days ) {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	$sql_select = "SELECT value FROM site WHERE setting = 'rawretentiondays' ;";
	if ( $result = $my_db->query($sql_select) ) {
		$row = $result->fetch_object();
		$db_rawretentiondays = $row->value;
		if ( $db_rawretentiondays > $days ) {
			$sql_update = "UPDATE site SET value = $db_rawretentiondays WHERE setting = 'rawretentiondays'; UPDATE site SET value = 1 WHERE setting = 'newgroupscanmethod'; UPDATE site SET value = 7 WHERE setting = 'newgroupdaystoscan' ;";
			if ( $my_db->multi_query($sql_update) === FALSE ) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
		}
		else {
			$sql_update = "UPDATE site SET value = $days WHERE setting = 'rawretentiondays'; UPDATE site SET value = 1 WHERE setting = 'newgroupscanmethod'; UPDATE site SET value = 7 WHERE setting = 'newgroupdaystoscan' ;";
			if ( $my_db->multi_query($sql_update) === FALSE ) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
		}
		$result->close();
	} else { echo "[ERROR]--------->$sql_select<---------\n***".$my_db->error."***\n"; }
	$my_db->close();
}

function update_release_post( $post_matches ) {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	foreach( $post_matches as $post_values ) {
		$releaseregex_regex_db = '/.*?(?P<name>(' .str_replace("'", "\'", str_replace('*', '.',str_replace('/', '\/', $post_values[2]) ) ). ').*?).*?/';
		$sql_select = "SELECT releases.ID , releases.name , releaseregex.categoryID FROM releases,releaseregex WHERE releases.regexID = releaseregex.ID AND releaseregex.regex = '$releaseregex_regex_db' ;";
		if ( $result = $my_db->query($sql_select) ) {
			if ( $result->num_rows > 0 ) {
				while( $row = $result->fetch_object() ) {
					$db_releases_ID = $row->ID;
					$db_releases_name = $row->name;
					$db_releaseregex_categoryID = $row->categoryID;
					$release_name_db = '_-_Title:' . $post_values[1] . '_-_Archive ' . $post_values[2] . '_-_Size ' . $post_values[3] . '_-_Date ' . $post_values[4] . '_-_Language ' . $post_values[12] . '_-_Quality ' . $post_values[13] . '_-_Source ' . $post_values[9] . '_-_Link ' . $post_values[18] . '_-_';
					$release_name_db = str_replace(  "'", "\'", iconv('ISO-8859-1', 'ASCII//TRANSLIT', $release_name_db) );
					if ( $db_releaseregex_categoryID[0] == '5' ) {
						$sql_update = "UPDATE releases SET rageID = '-1', name = '$release_name_db', searchname = '$release_name_db' WHERE ID = $db_releases_ID ;";
						echo "[INFO] Update release $db_releases_ID : $release_name_db \n";
						if ( $my_db->query($sql_update) === FALSE ) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
					}
					elseif ( $db_releaseregex_categoryID[0] == '2' ) {
						$release_name_regex = "/^(.*?)(3d|4k|[b|B]lu-ray|[V|v]ersion|[R|r]emastérisé|[M|m]astered|[L|l]'intégrale|\+|\(|\[).*(\d\d\d\d)\).*/";
						preg_match_all( $release_name_regex , $post_values[1] , $release_name_matches , PREG_SET_ORDER );
						$release_name = $release_name_matches[0][1] . ' ' . $release_name_matches[0][3];
						$imdb_id = correct_imdb( iconv('ISO-8859-1', 'ASCII//TRANSLIT', $release_name) );
						$sql_update = "UPDATE releases SET imdbID = $imdb_id, name = '$release_name_db', searchname = '$release_name_db' WHERE ID = $db_releases_ID ;";
						echo "\n\n[DEBUG] Update $imdb_id movie release $db_releases_ID : $release_name_db \n\n";
						if ( $my_db->query($sql_update) === FALSE ) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
						$movie = new Movie();
						$movie->updateMovieInfo($imdb_id);
					} else { echo "[ERROR]--------->CATEGORY NOT FOUND<---------\n"; }
				}
			}
		} else { echo "[ERROR]--------->$sql_select<---------\n***".$my_db->error."***\n"; }
		$result->close();
	}
}
	$my_db->close();

function correct_imdb( $release_name ) {
	$imdb_url = 'www.imdb.com/find?q=' . urlencode($release_name);
	echo "\n\n[DEBUG] ".$imdb_url."\n\n";
	$imdb_regex='/.*<a href="\/title\/tt(.*?)\/\?ref_=fn_al_tt_1".*/';
	preg_match_all( $imdb_regex , get_url($imdb_url) , $imdb_matches , PREG_SET_ORDER );
 	return $imdb_matches[0][1];
}

function add_group_post( $group_matches , $post_matches , $days ) {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	foreach ( $post_matches as $post_values ) {
		foreach( explode(' ',$post_values[14]) as $post_group ) {
			foreach ( $group_matches as $group_values ) {
			$post_group = str_replace('a.b.', 'alt.binaries.', $post_group);
			if ( $post_group == $group_values[1]  &&  $post_group != '' ) {
					$sql_select = 'SELECT active FROM groups WHERE name = \'' . $group_values[1] . '\' ;';
					if ( $result = $my_db->query($sql_select) ) {
						if ( $result->num_rows == 1 ) {
							$row = $result->fetch_object();
							$db_groups_active = $row->active;
							if ( $db_groups_active == 0 ) {
								echo "[INFO] Active $group_values[1] for $days day(s)\n";
								$sql_update = "UPDATE groups SET active = 1 , backfill_target = $days WHERE name = '$group_values[1]' ;";
								if ( $my_db->query($sql_update) === FALSE ) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
							}
						}
						elseif ( $result->num_rows == 0 ) {
							echo "[INFO] Add and Active $group_values[1] for $days day(s)\n";
							$sql_insert = "INSERT INTO groups ( name , backfill_target , active , description ) VALUES ( '$group_values[1]' , $days , 1 , 'post' ) ;";
							if ( $my_db->query($sql_insert) === FALSE ) { echo "[ERROR]--------->$sql_insert<---------\n***".$my_db->error."***\n"; }
						} else { echo "[ERROR]--------->DUPLICATE GROUP<---------\n"; }
					} else { echo "[ERROR]--------->$sql_select<---------\n***".$my_db->error."***\n"; }
					$result->close();
				}
			}
		}
	}
	$my_db->close();
}

function add_regex_post( $post_matches , $category) {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	foreach ( $post_matches as $post_values ) {
		if( strpos($post_values[1] , '*** MOT DE PASSE ***') == false ) {
			foreach( explode(' ',$post_values[14]) as $post_group ) {
				if ( $post_group != '' && $post_values[2] != '' ) {
					$post_group = str_replace('a.b.', 'alt.binaries.', $post_group);
					$sql_select = 'SELECT name FROM groups WHERE active = 1 AND name = \'' . $post_group . '\';';
					if ( $result = $my_db->query($sql_select) ) {
						if ( $result->num_rows == 1 ) {
							$releaseregex_regex_db = '/.*?(?P<name>(' .str_replace("'", "\'", str_replace('*', '.',str_replace('/', '\\\/', $post_values[2]) ) ). ').*?).*?/';
							echo "[INFO] Add and active regex $category : $post_group : $releaseregex_regex_db \n";
							$sql_insert = "INSERT INTO releaseregex (groupname , regex , status , description, categoryID) VALUES ('$post_group' , '$releaseregex_regex_db' , 1 , 'post' , '$category') ;";
							if ( $my_db->query($sql_insert) === FALSE ) { echo "[ERROR]--------->$sql_insert<---------\n***".$my_db->error."***\n"; }
						} else { echo "[ERROR]--------->$post_group DISABLE OR DUPLICATE GROUP<---------\n"; }
						$result->close();
					} else { echo "[ERROR]--------->$sql_select<---------\n***".$my_db->error."***\n"; }
				}
			}
		}
	}
	$my_db->close();
}

function del_regex_post() {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	$sql_delete="DELETE FROM releaseregex WHERE status = 1 AND description = 'post' ;";
	echo "[INFO] Delete all active post regex...\n";
	if ($my_db->query($sql_delete) === FALSE) { echo "[ERROR]--------->$sql_delete<---------\n***".$my_db->error."***\n"; }
	$my_db->close();
}

function disable_group_all() {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	$sql_update="UPDATE groups SET active = 0 ;";
	echo "[INFO] Disable all group...\n";
	if ($my_db->query($sql_update) === FALSE) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
	$my_db->close();
}

function disable_regex_all() {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	$sql_update="UPDATE releaseregex SET status = 0 ;";
	echo "[INFO] Disable all regex...\n";
	if ($my_db->query($sql_update) === FALSE) { echo "[ERROR]--------->$sql_update<---------\n***".$my_db->error."***\n"; }
	$my_db->close();
}

function clean_database() {
	$my_db = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	echo "[INFO] TABLE releaseregex TRUNCATE...\n";
	if ($my_db->query("TRUNCATE TABLE releaseregex ;") === FALSE) { echo "[ERROR]\n";	}
	echo "[INFO] TABLE releasenfo TRUNCATE...\n";
	if ($my_db->query("TRUNCATE TABLE releasenfo ;") === FALSE) { echo "[ERROR]\n"; }
	echo "[INFO] TABLE releases TRUNCATE...\n";
	if ($my_db->query("TRUNCATE TABLE releases ;") === FALSE) { echo "[ERROR]\n"; }
	echo "[INFO] TABLE movieinfo TRUNCATE...\n";
	if ($my_db->query("TRUNCATE TABLE movieinfo ;") === FALSE) { echo "[ERROR]\n"; }
	echo "[INFO] TABLE groups TRUNCATE...\n";
	if ($my_db->query("TRUNCATE TABLE groups ;") === FALSE) { echo "[ERROR]\n"; }
	echo "[INFO] TABLE binaries RESET...\n";
	if ($my_db->query("UPDATE binaries SET procstat = 0 , procattempts = 0 , categoryID = NULL , regexID = NULL , relpart = 0 , reltotalpart = 0 , relname = NULL , releaseID = NULL ;") === FALSE) { echo "[ERROR]\n"; }
	$my_db->close();
}

function get_url( $url ) {
	$c = curl_init();
	curl_setopt($c, CURLOPT_URL, $url);
	curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($c, CURLOPT_HEADER, false);
	$content = curl_exec($c);
	if($content === false) { trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING); }
	curl_close($c);
	//echo "[DEBUG] Content of $url : \n$content\n";
 	return $content;
}

echo "\n\nFinish in " . number_format(microtime(true)-$timestart, 3) . " sec\n\n";
?>

